var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const jwt = require('jsonwebtoken');

var emailFunc = require('./plugin/email');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var oilRouter = require('./routes/oil');
var goldRouter = require('./routes/gold');
var topSearchRouter = require('./routes/topSearch');
var documentRouter = require('./routes/document');
var articleRouter = require('./routes/article');
const { getGoldData } = require('./plugin/dataCrawler');


var app = express();

const CronJob = require('cron').CronJob;

// 创建一个新的定时任务实例
const job = new CronJob(
  '0 6 * * *', // 时间表达式
  async function () { // 执行的回调函数
    // console.log('每分钟执行一次');
    // console.log(app);
    // app.get('/api/gold/get', (error, data) => {
    //   // if (error) {
    //   //   return res.status(500).send(error);
    //   // }
    //   console.log(data);
    // })
    const { SJSData } = await getGoldData();

    console.log(SJSData[0].recentPrice);
    if (SJSData.length && SJSData[0].recentPrice) {
      const recentPrice = SJSData[0].recentPrice;
      if (+recentPrice < 540) {
        const eml = '2829262616@qq.com, 3258379404@qq.com';
        // 定义模版
        const email = {
          title: '金价信息',
          body: `
                    <h1>尊敬的用户</h1>
                    <p style="font-size: 18px;color:#000;">
                    今天的金价为：
                    <span style="font-size: 20px;color:#f00;"> ${recentPrice}， </span>
                    </p>
                    <p style="font-size: 1.5rem;color:#999;">可点击 https://m.ylmlove.site/ 查看金价信息</p>
                    `,
        };
        const emailCotent = {
          from: '3258379404@qq.com', // 发件人地址
          to: `${eml}`, // 收件人地址，多个收件人可以使用逗号分隔
          subject: email.title, // 邮件标题
          html: email.body, // 邮件内容
        };
        // console.log(email);
        emailFunc.sendEmail(emailCotent);// 该辅助方法在extend/helper.js中定义
      }
    }
  },
  true, // 可选参数，是否立即执行，默认为 false
  true, // 立即启动定时任务
  'UTC' // 时区，默认为系统时区
);

// 启动定时任务
job.start();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/api/file', express.static(path.join(__dirname, 'public/file')));
app.use(express.raw({
  type: 'application/octet-stream', // 确保处理二进制数据
  limit: '10mb' // 设置正文大小限制，具体尺寸根据实际需求调整
}));
app.use(express.raw({ type: 'application/x-protobuf' }));

// 接收 ArrayBuffer 数据的路由
app.post('/api/upload', (req, res) => {
  // 确保正确接收了二进制数据
  if (req.body instanceof Buffer) {
    const arrayBuffer = req.body.buffer; // 将 Buffer 转换为 ArrayBuffer
    console.log('Received ArrayBuffer:', arrayBuffer);

    // 处理接收到的 ArrayBuffer 数据...

    res.status(200).send('ArrayBuffer data received.');
  } else {
    res.status(400).send('Invalid data format.');
  }
});


app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'root' && password === '123456') {
    const token = jwt.sign({ username, password }, '123456', { expiresIn: '240h' });
    res.send({
      code: 1,
      data: {
        token,
        username
      },
      msg: '获取成功'
    })
  } else {
    res.send('Invalid credentials');
  }
});

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api/oil', oilRouter);
app.use('/api/gold', goldRouter);
app.use('/api/topSearch', topSearchRouter);
app.use('/api/document', documentRouter);
app.use('/api/article', articleRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
